//
//  HJStatusViewModel.swift
//  sinaWeibo
//
//  Created by hjun on 16/3/26.
//  Copyright © 2016年 hjun. All rights reserved.
//

import UIKit

import SDWebImage
class HJStatusViewModel: NSObject {
    
    static let sharedInstance: HJStatusViewModel = HJStatusViewModel()
    
    ///加载微博数据
    func loadStatus(since_id: Int64, max_id: Int64, loadCallBack:( status: [HJStatus]?, error: NSError?)-> ()){
        ///获取URL
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        ///请求参数
        
        var parameters: [String: AnyObject] = ["access_token": HJUserAccountViewModel.sharedInstance.userAccount!.access_token!]
        
        ///下拉刷新数据
        
        if since_id > 0{
            //返回比since_id大于0 需要下拉刷新
            ///注意字典里不能用INT64 需要转换成NSNumber 
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0{
            
            parameters[" max_id"] = NSNumber(longLong: max_id - 1)
        }
        
        
        
        //get请求
        HJNetWorkTool.sharedInstance.requestGET(urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil
            {
                print("请求错误")
                loadCallBack(status:nil, error: error)
                return
            }
            
            ///获得元素
            let statusArray = result?["statuses"] as? [[String: AnyObject]]
            
            //定义空数组来存放模型
            var statuses = [HJStatus]()
            
            ///遍历字典数组
            for dict in statusArray!{
                
                let status = HJStatus(dict: dict)
                
                statuses.append(status)
                
            }
            
            
            self.cacheImage(statuses, loadStatusCallBack: loadCallBack)
           
            
        }
        
    }
    
    ///缓存微博图片
    
    private func cacheImage(statuses: [HJStatus], loadStatusCallBack:(statuses: [HJStatus]?,error: NSError?)-> ()){
        
        ///创建group
        let group = dispatch_group_create()
        
        var length: CGFloat = 0
        
        ///查找微博里的图片 下载下来
        
        for status in statuses{
        
           var downUrls = status.picturesURL
        
            ///如果原创的没有 找转发的微博
            if downUrls == nil{
                
             downUrls = status.retweeted_status?.picturesURL
             
            }
            ///如果原创与转发都没有
            if downUrls == nil {
              ///切记不能用return 不然循环结束
                continue
                
            }
            
            ///此时到这里说明有图片
            ///并且只需要缓存一张图片
            
            if downUrls?.count == 1{
                ///取到第一张
                let url = downUrls![0]
                ///在异步之前进入组
                
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    ///离开组
                    dispatch_group_leave(group)
                    
                    if error != nil{
                        
                        HJPrint(msg: "下载图片失败")
                        return
                    }
                    
                    HJPrint(msg: "图片下载成功")
                    
                    let data = UIImagePNGRepresentation(image)
                    
                    length += CGFloat(data!.length)
                    
                })
                
                
            }

        }
        
        ///所有模型下载完通知
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            let len = length / 1024 / 1024.0
            
            let imageLength = String(format: "%.2f", arguments:[len])
            
            HJPrint(msg: "所有图片下载完成:\(imageLength)MB")
            
            loadStatusCallBack(statuses: statuses, error: nil)
        }
        
    }
    
}
